package com.qianyitian.hope2.analyzer.service;

import com.qianyitian.hope2.analyzer.analyzer.IStockAnalyzer;
import com.qianyitian.hope2.analyzer.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class StockGrader {
    private Logger logger = LoggerFactory.getLogger(getClass());
    List<IStockAnalyzer> analyzers = new ArrayList<IStockAnalyzer>();

    public StockGrader() {
    }

    public void addAnalyzer(IStockAnalyzer analyzer) {
        analyzers.add(analyzer);
    }

    public Map startGrade(Stock stock) {
        if (stock != null && !stock.getkLineInfos().isEmpty()) {
            return analyze(stock);
        }
        return null;
    }

    private Map analyze(Stock stock) {
        ResultInfo resultInfo = new ResultInfo();
        Map map = new HashMap<>();
        int total = 0;
        for (IStockAnalyzer analyzer : analyzers) {
            try {
                if (analyzer.analyze(resultInfo, stock)) {
                    int weight = analyzer.getWeight();
                    if (weight == 0) {
                        continue;
                    }
                    total += weight;
                    map.put(analyzer.getClass().getSimpleName(), weight);
                }
            } catch (Exception e) {
                logger.error("analyzer " + analyzer.getClass().getName() + " stock " + stock.getCode(), e);
            }
        }
        map.put("total", total);
        map.put("code", stock.getCode());
        map.put("name", stock.getName());
        return map;
    }
}
